package com.jiangyao.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jiangyao.common.ApiResult;
import com.jiangyao.common.annotation.Cache;
import com.jiangyao.common.constants.CacheConstants;
import com.jiangyao.common.exception.ServerException;
import com.jiangyao.common.utils.FtpClient;
import com.jiangyao.common.utils.MathUtil;
import com.jiangyao.common.utils.StringUtils;
import com.jiangyao.component.RedisComponent;
import com.jiangyao.model.dto.BannerDTO;
import com.jiangyao.model.dto.ClassUserDto;
import com.jiangyao.model.dto.UserDto;
import com.jiangyao.model.dto.UserExperienceDto;
import com.jiangyao.model.entity.*;
import com.jiangyao.model.vo.ExperienceVo;
import com.jiangyao.model.vo.HomeCountVo;
import com.jiangyao.model.vo.MyCountVo;
import com.jiangyao.model.vo.UserClassVo;
import com.jiangyao.model.vo.UserDynamicVo;
import com.jiangyao.model.vo.UserExperienceVo;
import com.jiangyao.model.vo.UserSessionVO;
import com.jiangyao.model.vo.UserSubjectVo;
import com.jiangyao.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.dozer.DozerBeanMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/user")
@Api(tags = "成员相关接口")
public class UserController extends BaseController {

	@Autowired
	ApiAccessLogService logService;

	@Autowired
	private UserService userService;

	@Autowired
	private BannerService bannerService;

	@Autowired
	private OrgInfoService orgInfoService;

	@Autowired
	private JobService jobService;

	@Autowired
	private ClassUserService classUserService;

	@Autowired
	private ClassUserScoreService classUserScoreService;

	@Autowired
	private ClassSemesterService classSemesterService;

	@Autowired
	private ClassSubjectService classSubjectService;

	@Autowired
	private ProgressService progressService;

	@Autowired
	private UserExperienceService userExperienceService;

	@Autowired
	private IntegralLogService integralLogService;

	@Autowired
	private DozerBeanMapper dozerBeanMapper;

	@Autowired
	private RedisComponent redisComponent;


	@Autowired
	private PublicProgressService publicProgressService;


	@ApiOperation(value = "退出登录", notes = "无传参")
	@PostMapping("/logout")
	public ApiResult<Boolean> logout() {
		redisComponent.del(CacheConstants.CACHE_KEY_TOKEN_API_PREFIX + getLoginToken());
		return new ApiResult<>(true);
	}

	@PostMapping("/bindOpenId")
	@ApiOperation(value = "绑定微信号和手机号（资阳版本）" ,notes = "必传openID")
	public ApiResult<Boolean> bindOpenId(@RequestBody UserDto userDto) {
		if(StringUtils.isBlank(userDto.getOpenId())){
			throw new ServerException(305, "未传入微信信息");
		}
		User user = new User();
		user.setUserId(getLoginSessionUserId());
		user.setOpenId(userDto.getOpenId());
		if(StringUtils.isBlank(userDto.getUnionId())){
			user.setUnionId(userDto.getUnionId());
		}
		userService.updateById(user);
		return new ApiResult<>(true);
	}

	@PostMapping("/getUserSession")
	@ApiOperation(value = "获取UserSession")
	public ApiResult<UserSessionVO> getUserSession() {
		return ApiResult.success(getLoginSession());
	}


	@PostMapping("/getUserInfo")
	@ApiOperation(value = "获取用户信息")
	public ApiResult<User> getUserInfo(@RequestBody UserDto userDto) {
		QueryWrapper<User> queryWrapper = new QueryWrapper<>();
		queryWrapper.lambda().eq(User::getUserId, userDto.getUserId());
		User user = userService.getOne(queryWrapper);
		user.setPassword(null);
		return ApiResult.success(user);
	}


	@PostMapping("/getBannerList")
	@ApiOperation(value = "banner列表")
	public ApiResult<List<Banner>> getBannerList(@RequestBody BannerDTO bannerDTO) {
		QueryWrapper<Banner> params = new QueryWrapper<>();
		params.eq("status", 1).orderByAsc("sort_order");
		if (StringUtils.isNotEmpty(bannerDTO.getBannerCode())) {
			params.eq("banner_code", bannerDTO.getBannerCode());
		}
		List<Banner> result = bannerService.list(params);
		if (!CollectionUtils.isEmpty(result)) {
			result.forEach(r -> r.setBannerImg(FtpClient.fullFtpUrl(r.getBannerImg())));
		}
		return ApiResult.success(result);
	}

	@PostMapping("/getHomeCount")
	@Cache(expire = 300)
	@ApiOperation(value = "首页统计信息")
	public ApiResult<HomeCountVo> getHomeCount() {
		HomeCountVo result = new HomeCountVo();

		QueryWrapper<OrgInfo> schoolParams = new QueryWrapper<>();
		schoolParams.eq("org_type", 1).eq("status", 1);

		QueryWrapper<OrgInfo> companyParams = new QueryWrapper<>();
		companyParams.eq("org_type", 2).eq("status", 1);

		QueryWrapper<Job> jobParams = new QueryWrapper<>();
		jobParams.eq("status", 1);

		QueryWrapper<Progress> proParams = new QueryWrapper<>();
		proParams.eq("status", 2);

		result.setOrgSchool(orgInfoService.count(schoolParams));
		result.setOrgCompany(orgInfoService.count(companyParams));
		result.setUserCount(userService.count());
		result.setJobCount(jobService.count(jobParams));
		result.setSkillsCount(progressService.count(proParams));
		result.setPVCount(logService.count());
		return ApiResult.success(result);
	}

	@PostMapping("/getUserCount")
	@ApiOperation(value = "我的页面统计信息-传orgId，classId")
	public ApiResult<MyCountVo> getUserCount() {
		User user = userService.getById(getLoginSessionUserId());

		QueryWrapper<User> lessUserCount = new QueryWrapper();
		lessUserCount.between("integral_num", 0, user.getIntegralNum() - 1);
		Integer lessCount = userService.count(lessUserCount);
		Integer allCount = userService.count();
		double high = MathUtil.divisionKeep(lessCount, allCount, 3);

		QueryWrapper<Progress> progressCount = new QueryWrapper();
		progressCount.eq("user_id", getLoginSessionUserId()).eq("status", 2);

		MyCountVo vo = new MyCountVo();
		vo.setMyIntegral(user.getIntegralNum());
		vo.setHighPercent(high * 100);
		vo.setHourCount(progressService.count(progressCount));
		vo.setYearCount(userExperienceService.getUserExperienceWorkTear());
		return ApiResult.success(vo);
	}

	@PostMapping("/getUserDynamic")
	@ApiOperation(value = "成员动态")
	public ApiResult<List<UserDynamicVo>> getUserDynamic() {
		return ApiResult.success(userService.getUserDynamic());
	}

	@PostMapping("/getUserOrgClass")
	@ApiOperation(value = "成员班级信息")
	public ApiResult<List<UserClassVo>> getUserOrgClass() {
		return ApiResult.success(classUserService.getWebUserClass());
	}

	@PostMapping("/getUserOrg")
	@ApiOperation(value = "成员组织信息")
	public ApiResult<List<OrgInfo>> getUserOrg() {
		return ApiResult.success(orgInfoService.getSessionUserOrg());
	}

	@PostMapping("/getUserScore")
	@ApiOperation(value = "成员专业课程学分")
	public ApiResult<UserSubjectVo> getUserScore(@RequestBody ClassUserDto dto) {
		UserSubjectVo vo = new UserSubjectVo();
		vo.setIntegral(integralLogService.getIntegralSumByType(7));
		QueryWrapper<ClassUserScore> params = new QueryWrapper();
		params.eq("org_id", dto.getOrgId()).eq("class_id", dto.getClassId()).eq("user_id", getLoginSessionUserId());
		List<ClassUserScore> list = classUserScoreService.list(params);
		Map<String, List<ClassUserScore>> groupBy = list.stream().collect(Collectors.groupingBy(ClassUserScore::getSemesterName));
		vo.setSubjectMap(groupBy);
		return ApiResult.success(vo);
	}

	@PostMapping("/getUserClassSubject")
	@ApiOperation(value = "成员专业课程学分")
	public ApiResult<UserSubjectVo> getUserClassSubject(@RequestBody ClassUserDto dto) {
		return ApiResult.success(classSemesterService.getUserClassSubject(dto));
	}

	@PostMapping("/getUserExperience")
	@ApiOperation(value = "成员个人经历")
	public ApiResult<ExperienceVo> getUserExperience(@RequestBody ClassUserDto dto) {
		return ApiResult.success(userExperienceService.getUserExperience(dto));
	}

	@PostMapping("/getUserPublicSubject")
	@ApiOperation(value = "成员公开课信息")
	public ApiResult<List<PublicProgress>> getUserPublicSubject() {
		return ApiResult.success(publicProgressService.getUserPublicSubject());
	}

	@PostMapping("/getUserExperienceByType")
	@ApiOperation(value = "通过type成员个人经历-必传type")
	public ApiResult<List<UserExperience>> getUserExperienceByType(@RequestBody UserExperienceDto dto) {
		if (dto.getType() == null) {
			throw new ServerException(302, "参数不正确");
		}
		QueryWrapper<UserExperience> params = new QueryWrapper<>();
		params.eq("type", dto.getType()).eq("user_id", getLoginSessionUserId()).eq("status", 2).orderByDesc("start_time");
		List<UserExperience> list = userExperienceService.list(params);
		List<UserExperienceVo> result = new ArrayList<>();
		for (UserExperience domain : list) {
			UserExperienceVo vo = dozerBeanMapper.map(domain, UserExperienceVo.class);
			vo.setCredentialsFullUrl(vo.getCredentials());
			result.add(vo);
		}
		return ApiResult.success(result);
	}

	@PostMapping("/getUserExperienceById")
	@ApiOperation(value = "通过Id修改成员个人经历-必传id")
	public ApiResult<UserExperience> getUserExperienceById(@RequestBody UserExperienceDto dto) {
		if (dto.getId() == null) {
			throw new ServerException(302, "参数不正确");
		}
		QueryWrapper<UserExperience> params = new QueryWrapper<>();
		params.eq("id", dto.getId()).eq("user_id", getLoginSessionUserId());
		params.last("limit 1");
		UserExperience info = userExperienceService.getOne(params);
		UserExperienceVo result = dozerBeanMapper.map(info, UserExperienceVo.class);
		result.setCredentialsFullUrl(FtpClient.fullFtpUrl(result.getCredentials()));
		return ApiResult.success(result);
	}

	@PostMapping("/updateUserExperience")
	@ApiOperation(value = "修改成员个人经历")
	public ApiResult<Boolean> updateUserExperience(@Validated({UserExperienceDto.Edit.class}) @RequestBody UserExperienceDto dto) {
		UserExperience info = dozerBeanMapper.map(dto, UserExperience.class);
		info.setStatus(1);
		userExperienceService.updateById(info);
		return ApiResult.success(true);
	}

	@PostMapping("/addUserExperience")
	@ApiOperation(value = "新增成员个人经历")
	public ApiResult<Boolean> addUserExperience(@Validated({UserExperienceDto.Add.class}) @RequestBody UserExperienceDto dto) {
		UserExperience info = dozerBeanMapper.map(dto, UserExperience.class);
		info.setUserId(getLoginSessionUserId());
		info.setStatus(1);
		info.setCreateTime(new Date());
		userExperienceService.save(info);
		return ApiResult.success(true);
	}


}

